/*!
 * fawave - ui.js
 * Copyright(c) 2012 fengmk2 <fengmk2@gmail.com>
 * MIT Licensed
 */

"use strict";

/**
 * Module dependencies.
 */

var i18n = require('./i18n');
var User = require('./user');
var Shotenjin = require('./lib/shotenjin');
var provinces = require('./provinces');
var moment = require('moment');
var emoji = require('weibo/node_modules/emoji');

function getUserCountsInfo(user) {
    if (user.statuses_count === undefined) {
        return '';
    }
    return '关注' + '：' + user.friends_count + '\r\n' +
        '粉丝' + '：' + user.followers_count + '\r\n' +
        '微博' + '：' + user.statuses_count + '';
}

//格式化时间输出。示例：new Date().format("yyyy-MM-dd hh:mm:ss");
Date.prototype.format = function (format) {
    var o = {
        "M+" : this.getMonth() + 1, //month
        "d+" : this.getDate(),    //day
        "h+" : this.getHours(),   //hour
        "m+" : this.getMinutes(), //minute
        "s+" : this.getSeconds(), //second
        "q+" : Math.floor((this.getMonth() + 3) / 3), //quarter
        "S" : this.getMilliseconds() //millisecond
    };
    if (/(y+)/.test(format)) {
        format = format.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
    }

    for (var k in o) {
        if (new RegExp("(" + k + ")").test(format)) {
            format = format.replace(RegExp.$1, RegExp.$1.length === 1 ? o[k] : ("00" + o[k]).substr(("" + o[k]).length));
        }
    }
    return format;
};
var STRING_FORMAT_REGEX = /\{\{([\w\s\.\'\"\(\),-\[\]]+)?\}\}/g;
var format = function (s, values) {
    var cb;
    if (typeof values === 'function') {
        cb = values;
    } else {
        cb = function (match, key) {
            try {
                return values[key] || eval('(values.' + key + ')');
            } catch (e) {
                console.log(JSON.stringify([s, values, key]));
                // return s;
                throw e;
            }
        };
    }
    return s.replace(STRING_FORMAT_REGEX, cb);
};
var EMOTION_TPL = '<img title="{{title}}" src="{{src}}" />';
var load_emotions = function () {
    {
        var em = require('weibo/lib/emotional');    //todo
        var em_face = em.faces;
        //var em_weibo = em_face.tsina;
        //var em_weibo = em_face[1];    //not work
        var em_weibo = em_face.weibo;
        var em_em = em_weibo[0];
        //var em_haha = em_em[2];
        //var tt1 = em_weibo[0];
        //var tt3 = em_weibo[0][1];
        //var tt4 = em_weibo[0]['good'];
        //var tt6 = em_weibo[0][good];
        //var tt2 = em_weibo[0][g1];
        //var tt = em_weibo[g1];
        //var em_haha1 = em_em.good;
        //console.log('em.weibo:'+em_haha);
        //console.log('em.tsina:'+em.tsina);
        //var _emotions = em.weibo;
        //var _emotions = em[this.blogtype] || em.weibo;
        //console.log('em._emotions:'+_emotions);
    }
    return em_weibo;
};
/* emotion gif instead of emotion text */
var replace_emotional = function (m, g1) {
    if (!g1) {
        return m;
    }
    console.log('g1'+g1);
    var emotions = load_emotions();
    console.log('returns_motional:'+emotions);
    var face = emotions && emotions[0][g1];
    console.log(face+':'+emotions[0][g1]+emotions[1]);
    var uurl = emotions[1];
    if (face) {
        var url = emotions[1] + face;
        console.log('emotions emotions url='+url);
        return format(EMOTION_TPL, { title: m, src: url });
    }
    return m;
};
var process_emotional = function (text) {
    return text.replace(/\[([\u4e00-\u9fff,\uff1f,\w]{1,6})\]/g, replace_emotional);
};
var escape = function (html) {
    return String(html)
        .replace(/&(?!\w+;)/g, '&amp;')
        .replace(/</g, '&lt;')
        .replace(/>/g, '&gt;')
        .replace(/"/g, '&quot;');
};

var process_emoji = function (text) {
    return emoji.unifiedToHTML(emoji.softbankToUnified(text));
};
var URL_RE = new RegExp('(?:\\[url\\s*=\\s*|)((?:www\\.|http[s]?://)[\\w\\.\\?%&\\-/#=;:!\\+~]+)(?:\\](.+)\\[/url\\]|)', 'ig');
var _replace_url = function (m, g1, g2) {
    var url = g1;
    if (g1.indexOf('http') !== 0) {
        url = 'http://' + g1;
    }
    var tpl = '<a class="status_text_link" href="{{url}}">{{value}}</a>';
    //console.log('_replace_url coming');
    return format(tpl, { url: url, title: g1, value: g2 || g1 });
};
var search_url = 'http://s.weibo.com/weibo/';
var SearchMatchReg = /#([^#]+)#/g;
var removeHTML = function (s) {
    return s.replace(/(<.*?>)/ig, '');
};
var process_search = function (text) {
    console.log('process_search coming');
    var url = search_url;
    return text.replace(SearchMatchReg, function (m, g1) {
        // fixed #xxx@xxx# nesting problem
        var search = removeHTML(g1);
        var tpl = '<a href="{{url}}{{searchEncode}}" class="status_hash_link" title="Search #{{search}}#">#{{search}}#</a>';
        return format(tpl, {search: search, searchEncode: encodeURIComponent(search), url: url});
    });
};
var AT_USER_RE = /([^#])?@([\w\-\_]+)/g;
var ONLY_AT_USER_RE = /@([\w\-\_]+)/g;
var process_at = function (text, users) { //@***
    var tpl = '{{pre}}<a class="at_user_link" href="' +
        search_url + '{{uid}}" data-uid="{{uid}}">@{{screen_name}}</a>';
    var homeurl = search_url;
    return text.replace(AT_USER_RE, function (match, m1, m2) {
        var uid = m2;
        var username = users[uid];
        if (username) {
            username += '(@' + uid + ')';
        } else {
            username = uid;
        }
        var data = {
            pre: m1 || '',
            url: homeurl + uid,
            uid: uid,
            screen_name: username
        };
        return format(tpl, data);
    });
};
var process_text = function (status) {
    //console.log('process_text --- process_text: status==' + status.text);
    var text = typeof status === 'string' ? status : status.text;
    if (!text) {
        return '&nbsp;';
    }

    text = escape(text);
    text = text.replace(URL_RE, _replace_url);  /* encode */
    text = process_at(text, status.users || {}); //@***
    text = process_emotional(text);
    console.log('process_text --- text==' + text);
    text = process_search(text); //#xxXX#
    console.log('process_search --- text==' + text);
    text = process_emoji(text);

    //text = this.process_at(text); //@***
    //text = this.process_search(text); //#xxXX#

    return text || '&nbsp;';
};

function buildStatusHtml(statuses, timeline, c_user) {
    var htmls = [];
    var rt_replace_pre = null, rt_rt_replace_pre = null;
    rt_replace_pre = '<!-- {{retweeted_status_in}} -->';
    rt_rt_replace_pre = '<!-- {{retweeted_retweeted_status_in}} -->';
    var _BUTTON_TPLS = {

        repostBtn: '<a class="reposttweet" href="javascript:void(0);" ' +/*转发这条微薄*/
        ' data-id="#{tweet.id}" title="' + i18n.get("btn_repost_title") + '">' + i18n.get("abb_repost") + '</a>',
        repostCounts: '<span class="repostCounts"><a href="javascript:void(0);" title="查看转发" data-type="repost">(#{tweet.reposts_count})</a></span>',/*转发的条数*/



        commentBtn: '<a class="commenttweet" href="javascript:void(0);" ' +
        ' data-id="#{tweet.id}" data-uid="#{tweet.user.id}" data-screen_name="#{tweet.user.screen_name}" ' +
        ' title="' + i18n.get("btn_comment_title") + '">' + i18n.get("abb_comment") + '</a>',/*点击添加评论*/
        commentCounts: '<span class="commentCounts"><a href="javascript:void(0);" title="点击查看评论" data-type="comment">(#{tweet.comments_count})</a></span>',/*转发的条数*/

        addFavoritesMsgBtn: '<a class="add_favorite_btn" data-id="#{tweet.id}" title="' +
        i18n.get("btn_add_favorites_title") + '"><img src="images/favorites_2.gif" /></a>',/*点击收藏*/
        delFavoritesMsgBtn: '<a class="del_favorite_btn" data-id="#{tweet.id}" title="' +
        i18n.get("btn_del_favorites_title") + '"><img src="images/favorites.gif"/></a>',/*点击取消收藏*/

        rtRepostBtn: '<a class="reposttweet" href="javascript:void(0);" ' +
        ' data-id="{{retweeted_status.id}}" title="' + i18n.get("btn_repost_title") + '">' + i18n.get("abb_repost") + '</a>',/*转发这条微薄*/
        rtRepostCounts: '<span class="repostCounts">({{retweeted_status.reposts_count}})</span>',/*转发的条数*/

        rtCommentBtn: '<a class="commenttweet" href="javascript:void(0);" ' +
        ' data-id="{{retweeted_status.id}}" data-uid="{{retweeted_status.user.id}}" data-screen_name="{{retweeted_status.user.screen_name}}" ' +
        ' title="' + i18n.get("btn_comment_title") + '">' + i18n.get("abb_comment") + '</a>',/*点击添加评论*/
        rtCommentCounts: '<span class="commentCounts">({{rt_comments_count}})</span>',/*评论数*/

        rtAddFavoritesMsgBtn: '<a class="add_favorite_btn" data-id="{{retweeted_status.id}}" title="' +
        i18n.get("btn_add_favorites_title") + '"><img src="images/favorites_2.gif"/></a>',/*点击收藏*/
        rtdelFavoritesMsgBtn: '<a class="del_favorite_btn" data-id="{{retweeted_status.id}}" title="' +
        i18n.get("btn_del_favorites_title") + '"><img src="images/favorites.gif"/></a>'/*点击取消收藏*/

    };
    if (!statuses || statuses.length === 0) {
        return htmls;
    }
    if (!c_user) {
        c_user = getUser();
    }
    var BUTTON_TPLS = $.extend({}, _BUTTON_TPLS);
    for (var i = 0, len = statuses.length; i < len; i++) {
        var status = statuses[i];
        status.user = status.user || status.sender || {};
        status.is_me = status.user.id === c_user.id;
        status.reposts_count = status.reposts_count || 0;

        /*判断是否是自己的微博信息*/
/*
        if (c_user && status.user && c_user.id === status.user.id) {
            status.myTweet = true;
        }
*/

        var rt_status = status.retweeted_status = status.retweeted_status || status.status;
        if (status.retweeted_status) {
            status.retweeted_status.user = status.retweeted_status.user || {};
        }
        status.comments_count = status.comments_count || 0;
        status.rt_comments_count = status.rtrt_comments_count = '-';
        if (rt_status && rt_status.user) {
            rt_status.reposts_count = rt_status.reposts_count || 0;
            rt_status.comments_count = rt_status.comments_count || 0;
            status.retweeted_status_screen_name = rt_status.user.screen_name;
            status.retweeted_status_id = rt_status.id;
        } else {
            status.retweeted_status_id = status.retweeted_status_screen_name = '';
        }

        var buttons = {};
        var tpl;
        for (var key in BUTTON_TPLS) {
            tpl = BUTTON_TPLS[key];
            var map_status = status;
            if (tpl) {
                tpl = Shotenjin.render(tpl, {tweet: status});
            }
            buttons[key] = tpl;
        }
        /*收藏按钮显示*/
        if(timeline === 'favorites'){/*如果是收藏列表*/
            buttons.addFavoritesMsgBtn = '';
        }else{
            if (status.favorited_at || status.favorited) {
                buttons.addFavoritesMsgBtn = '';
            } else {
                buttons.delFavoritesMsgBtn = '';
            }
        }
        var context = {
            provinces: provinces,
            //tType: status_type,
            getUserCountsInfo: getUserCountsInfo,
            buildTipboxUserInfo: buildTipboxUserInfo,
            //processMsg: tapi.process_text.bind(tapi),
            processMsg: process_text,
            user: status.user,
            account: c_user,
            tweet: status,

            is_rt_rt: true,/*false：评论,true：转发*/
            //support_follow: support_follow,
            show_fullname: false,
            //support_instapaper: support_instapaper,
            //support_readitlater: support_readitlater,
            btn: buttons
        };
        try {
            var html = Shotenjin.render(window.TEMPLATE, context);
            if (rt_status) {/*转发部分*/
                rt_status.user = rt_status.user || {};
                html = html.replace(rt_replace_pre, Shotenjin.render(window.TEMPLATE_RT, context));
                /*转发的转发部分*/

                if (rt_status.retweeted_status) {
                    context.is_rt_rt = true;
                    // context.retweeted_status_user = rt_status.user || {};
                    rt_status.retweeted_status.user = rt_status.retweeted_status.user || {};
                    context.tweet = rt_status;
                    html = html.replace(rt_rt_replace_pre, Shotenjin.render(window.TEMPLATE_RT, context));
                }

            }
            htmls.push(html);
        } catch (err) {
            // throw err;
            console.error(err);
        }

        status.readed = true;
    }
    return htmls;
}
exports.buildStatusHtml = buildStatusHtml;
// 生成Tipbox用户信息(鼠标移到用户头像时显示的用户信息)
function buildTipboxUserInfo(user, show_fullname) {
    var context = {
        provinces: provinces,
        user: user,
        show_fullname: show_fullname
    };
    return Shotenjin.render(window.TEMPLATE_TIPBOX_USER_INFO, context);
}

function showTips(message) {
    var tip = $('#msgInfoWarp .messageInfo');
    if (tip.length === 0) {
        $('<div class="messageInfo"></div>')
            .appendTo('#msgInfoWarp');
        tip = $('#msgInfoWarp .messageInfo');
    }
    tip.html(message);
    if (tip.is(':hidden')) {
        tip.fadeIn('slow')
            .animate({opacity: 1.0}, 3000)
            .fadeOut('slow');
    }
}
exports.showTips = showTips;

function showErrorTips(err) {
    var message = err.name + ': ' + err.message;
    showTips(message);
}
exports.showErrorTips = showErrorTips;

function buildItem(user, item, isComment) {
    var verified = '';
    if (item.user.verified) {
        verified = '<img title="' + i18n.get("comm_verified") + '" src="images/verified' +
            (item.user.verified_type && item.user.verified_type > 0 ? '_blue.png' : '.gif') + '" />';
    }
    return Shotenjin.render(window.TEMPLATE_COMMENT_ITEM, {
        item: item,
        isComment: isComment,
        verified: verified,
        text: item.text,
        created_at: moment(item.created_at).format("YYYY-MM-DD HH:mm:ss")
    });
}

exports.buildComment = function (user, item) {
    return buildItem(user, item, true);
};

exports.buildRepost = function (user, item) {
    return buildItem(user, item, false);
};

